package personal.zq.practice.common.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Slf4j
public class FileCleanUtil {

    private FileCleanUtil() {
    }

    /**
     * 删除文件
     *
     * @param directory
     * @param filePattern
     * @param excludes
     * @param maxFileNum
     */
    public static void deleteAncientFilesIfExists(String directory, final String filePattern, Set<String> excludes, int maxFileNum) {
        log.info(" start to remove ancient Files. directory = {}  pattern = {}", directory, filePattern);
        if (StringUtils.isEmpty(filePattern)) {
            return;
        }
        // 找出久远日志文件列表
        File dir = Paths.get(directory).toFile();
        File[] ancientFiles = dir
                .listFiles(file -> file.getName().matches(filePattern));
        if (ancientFiles == null || ancientFiles.length == 0) {
            return;
        }
        Arrays.stream(ancientFiles)
                .sorted(Comparator.comparing(File::lastModified).reversed())
                .skip(maxFileNum)
                .forEach(f -> {
                    try {
                        // 文件存在并且不在例外列表
                        if (Files.exists(Paths.get(f.getAbsolutePath())) && (CollectionUtils.isEmpty(excludes) || !excludes.contains(f.getName()))) {
                            log.info(" 准备删除的文件：{}", f.getName());
                            Files.delete(Paths.get(f.getAbsolutePath()));
                        }
                    } catch (IOException e) {
                        log.error(" {}, 文件删除错误: ", f.getPath(), e);
                    }
                });
    }


    /**
     * 删除空文件
     *
     * @param filePattern 空文件名匹配字符串
     */
    public static void deleteEmptyFile(String directory, String filePattern) {
        log.info(" start to remove empty Files. directory = {}  pattern = {}", directory, filePattern);
        Path dir = Paths.get(directory);
        if (!Files.exists(dir)) {
            return;
        }
        try (Stream<Path> stream = Files.list(dir)) {
            // 移除数据
            List<File> fileList = stream.map(Path::toFile)
                    .filter(file -> file.getName().matches(filePattern))
                    .filter(file -> file.length() == 0)
                    .collect(Collectors.toList());

            if (CollectionUtils.isEmpty(fileList)) {
                return;
            }
            for (File file : fileList) {
                log.info(" file.name = {} size = {} , will delete", file.getName(), file.length());
                file.delete();
            }
        } catch (Exception e) {
            log.error(" 空文件删除异常", e);
        }
    }
}
